package cn.huijielong.modules.oss.cloud;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.aliyun.oss.model.DeleteObjectsResult;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import cn.huijielong.common.exception.VSException;
import cn.huijielong.modules.oss.entity.Oss;

public class AliyunCloudStorage extends CloudStorage {

	private final static long expiration=1000*60*60*24;
	private OSSClient client;

    public AliyunCloudStorage(Oss oss,String bucket){
        this.oss = oss;
        this.ossBucket=oss.getBucket(bucket);

        //初始化
        init();
    }

    private void init(){
        client = new OSSClient(oss.getAliyunEndPoint(), oss.getAliyunAccessKeyId(),
        		oss.getAliyunAccessKeySecret());
    }

    @Override
    public String upload(byte[] data, String path) {
        return upload(new ByteArrayInputStream(data), path);
    }

    @Override
    public String upload(InputStream inputStream, String path) {
        try {
            client.putObject(ossBucket.getBucketName(), path, inputStream);
        } catch (Exception e){
            throw new VSException("上传文件失败，请检查配置信息", e);
        }

        return ossBucket.getDomain() + "/" + path;
    }

	@Override
	public String getPrivateUrl(String fileKey) {
		if(StringUtils.isEmpty(fileKey)) {
			return "";
		}
		if(fileKey.startsWith(ossBucket.getDomain())) {
			fileKey=fileKey.substring(ossBucket.getDomain().length()+1);
		}
		long time=new Date().getTime() + expiration;
		Date expiration = new Date(time);
		URL url = client.generatePresignedUrl(ossBucket.getBucketName(), fileKey, expiration);
		return url.toString();
	}

	@Override
	public boolean deleteBatch(String... path) {
		DeleteObjectsResult deleteObjectsResult = client.deleteObjects(
                new DeleteObjectsRequest(ossBucket.getBucketName()).withKeys(Arrays.asList(path)));
        List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
		return deletedObjects.size()>0;
	}

	@Override
	public boolean deleteBatch(String bucket, String... path) {
		DeleteObjectsResult deleteObjectsResult = client.deleteObjects(
                new DeleteObjectsRequest(bucket).withKeys(Arrays.asList(path)));
        List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
		return deletedObjects.size()>0;
	}

	@Override
	public void close() {
		client.shutdown();
	}
	
}
